package com.iwhalecloud.uncc.dao;

import com.iwhalecloud.uncc.common.SysConstant;
import com.iwhalecloud.uncc.model.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Author xu.dangling
 * @Date 2021/3/19
 */
@Repository
@ConditionalOnProperty(name = "loadFromDb", havingValue = "true", matchIfMissing = true)
public class AbstractDao {

    protected String dbType;

    @Autowired
    protected JdbcTemplate jdbcTemplate;

    @Autowired
    private SysConfigDao sysConfigDao;

    @PostConstruct
    public void init(){
        this.dbType = sysConfigDao.getSysConfig(SysConstant.DATABASE_TYPE);
    }

    /**
     * 分页查询
     *
     * @param sql       查询条件sql
     * @param countSql  统计数量的sql
     * @param paraList  查询参数
     * @param pageIndex 起点
     * @param pageSize  数量
     * @param rowMapper 结果类
     * @return
     */
    public <T> Page queryForPage(String sql, String countSql, List paraList, Integer pageIndex, Integer pageSize, RowMapper<T> rowMapper, JdbcTemplate jdbcTemplate) {
        Long count = jdbcTemplate.queryForObject(countSql, Long.class, paraList.toArray());
        Long beginNum = Integer.valueOf((pageIndex - 1) * pageSize).longValue();

        StringBuffer querySql = new StringBuffer();
        if ("mysql".equalsIgnoreCase(dbType)) {
            querySql.append(sql);
            querySql.append(" LIMIT ?,? ");

            paraList.add(beginNum);
            paraList.add(pageSize);
        } else if ("oracle".equalsIgnoreCase(dbType)) {
            querySql.append("SELECT * FROM (SELECT T2.* ,ROWNUM RN FROM (");
            querySql.append(sql);
            querySql.append(" ) T2 WHERE ROWNUM <= ? ) WHERE RN > ? ");

            Long endNum = beginNum + pageSize;
            paraList.add(endNum);
            paraList.add(beginNum);
        }

        List<T> retList = new ArrayList<T>();
        retList = jdbcTemplate.query(querySql.toString(), paraList.toArray(), rowMapper);

        Page<T> ret = new Page(retList, pageSize, count, pageIndex);
        return ret;
    }

}
